from django.shortcuts import render,HttpResponse
from myadmin.models import Users  #导入后台中的会员模型
from django.contrib.auth.hashers import make_password, check_password
from django.http import JsonResponse

#注册
def reg(request):
    if request.method=="POST":
        try:
            #print(request.POST.get('username'))
            if request.POST.get('nikename') and request.POST.get('phone') and request.POST.get('password'):
                pass
            else:
                return HttpResponse('<script>alert("注册失败,缺少必备选项");location.href="/reg"</script>')
            data=request.POST.dict()

            #短信验证
            msgcode = request.session['msgcode']
            if data['vcode'] == msgcode['code'] and data['phone'] == msgcode['phone']:
                pass
            else:
                return HttpResponse('<script>alert("注册失败,验证码错误");location.href="/reg"</script>')

            data.pop('csrfmiddlewaretoken')
            #短信验证码字段删除
            data.pop('vcode')
            #入库
            data['password'] = make_password(data['password'], None, 'pbkdf2_sha256')
            ob=Users(**data)
            ob.save()
            return HttpResponse('<script>alert("注册成功");location.href="/log"</script>')
        except:
            return HttpResponse('<script>alert("注册失败");location.href="/reg"</script>')
    else:
        return render(request, 'myhome/reg.html')

#登录
def log(request):
    if request.method=="POST":
        try:
            #phone = request.POST.get('phone')
            ob=Users.objects.get(phone=request.POST['phone'])
            #查询用户
            res=check_password(request.POST.get('password'),ob.password)
            #验证通过
            if res:
                request.session['VipUser'] = {'uid': ob.id, 'nikename': ob.nikename, 'phone': ob.phone,'pic_url': ob.pic_url}
                if request.GET.get('next'):
                    return HttpResponse('<script>alert("登录成功");location.href="{url}"</script>'.format(url=request.GET.get('next')))

                return HttpResponse('<script>alert("登录成功");location.href="/index"</script>')
            else:
                return HttpResponse('<script>alert("登录失败");location.href="/log"</script>')
        except:
            return HttpResponse('<script>alert("登录失败");location.href="/log"</script>')
    else:
        return render(request, 'myhome/log.html')

#短信发送
def send_Msg(request):
    import random

    #接受手机号码
    phone=request.GET.get('phone')
    #随机验证码
    code=str(random.randint(10000,99999))
    #把验证码存入session
    request.session['msgcode']={'code':code,'phone':phone}

    #调用方法  发送短信验证
    res=hywx_send(phone,code)

    #返回ajax 调用处
    return  JsonResponse(res)


def hywx_send(mobile, code):
    # 接口类型：互亿无线触发短信接口，支持发送验证码短信、订单通知短信等。
    # 账户注册：请通过该地址开通账户http://user.ihuyi.com/register.html
    # 注意事项：
    # （1）调试期间，请用默认的模板进行测试，默认模板详见接口文档；
    # （2）请使用 用户名 及 APIkey来调用接口，APIkey在会员中心可以获取；
    # （3）该代码仅供接入互亿无线短信接口参考使用，客户可根据实际需要自行编写；

    # import urllib2
    import urllib
    import urllib.request
    import json

    # 用户名 查看用户名请登录用户中心->验证码、通知短信->帐户及签名设置->APIID
    account = "C31736244"
    # 密码 查看密码请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
    password = "a46a4ea55f50c61e36197aac9c991f0f"
    # mobile = request.GET.get('phone')

    text = "您的验证码是：" + code + "。请不要把验证码泄露给其他人。"
    data = {'account': account, 'password': password, 'content': text, 'mobile': mobile, 'format': 'json'}
    req = urllib.request.urlopen(
        url= 'http://106.ihuyi.com/webservice/sms.php?method=Submit',
        data= urllib.parse.urlencode(data).encode('utf-8')
    )
    # 获取接口响应的内容
    content = req.read()
    res = json.loads(content.decode('utf-8'))

    #res = {'code': 2, 'msg': '提交成功', 'id': '1111', 'yzm': code}
    return res

#退出登录
def logout(request):
    del request.session['VipUser']
    return HttpResponse('<script>alert("退出登录");location.href="/";</script>')